﻿
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

using System.Security.Cryptography;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Net.Sockets;
using System.Threading;

using System.Net.Http.Headers;
using System.Net.Mail;
using System.Security.Policy;
using static System.Runtime.CompilerServices.RuntimeHelpers;
using static System.Net.Mime.MediaTypeNames;




/// <summary>
/// 云星辰的单据查询接口V1,友佳建材正在用
/// 这是云星辰V1的api，可以继续使用，但是金蝶官方不在维护，而且调用没有封装。已经跟换为V2接口
/// 仅保留参考。
/// </summary>

namespace Kingdee.API.TGTEST;
public class K3ApiRepositoryV1
{


    private string ClientID = "268149";
    private string ClientSecret = "5074b575301cbf8b694e46f90f0e0db5";
    private string outerInstanceId = "227496776318455808";

    private AcctInfo acctInfo = null;

    private string appToken = null;
    private string accessToken = null;

    private string token = "";


    public K3ApiRepositoryV1()
    {
        initToken();
    }


    #region 友佳建材的获取客户和物料基础资料，导入销售出库单。
    // 查询所有客户
    public List<CustModel> GetCustListSum()
    {

        List<CustModel> tmp1 = new List<CustModel>();

        var jSetting = new JsonSerializerSettings();
        jSetting.NullValueHandling = NullValueHandling.Ignore;

        int i = 1;
        while (true)
        {          // 预查寻
            string tmp2 = GetCustList(i);
            if (JObject.Parse(tmp2)["success"].Value<string>().ToUpper().Equals("TRUE"))
            {
                string oo = JObject.Parse(tmp2)["data"]["rows"].ToString();
                tmp1.AddRange(JsonConvert.DeserializeObject<List<CustModel>>(oo, jSetting));

                int sum = JObject.Parse(tmp2)["data"]["totalpage"].Value<int>();
                if (sum == i)
                {
                    break;
                }
            }
            i = i + 1;

        }
        return tmp1;
    }

    public string GetCustList(int page)
    {

        string jsonDate = "{  " +
            "	\"pagesize\":100000,  " +
            "        \"page\":" + page + ",  " +
            "        \"group\":[],  " +
            "        \"startdate\" :\"\" ,  " +
            "        \"enddate\" :\"\" ,  " +
            "        \"starttime\":-1,  " +
            "        \"endtime\":-1,  " +
            "        \"orderby\":\"\",  " +
            "        \"search\":\"\"  " +
            "}  ";




        string url = "http://api.kingdee.com/jdy/basedata/customer_list?access_token=" + accessToken;

        string rt = "";
        rt = postCustApiClient(url, jsonDate);
        return rt;

    }


    /*获取物料*/
    public List<MatModel> GetMatListSum()
    {
        List<MatModel> tmp1 = new List<MatModel>();

        var jSetting = new JsonSerializerSettings();
        jSetting.NullValueHandling = NullValueHandling.Ignore;

        int i = 1;
        while (true)
        {          // 预查寻
            string tmp2 = GetMatList(i);
            if (JObject.Parse(tmp2)["success"].Value<string>().ToUpper().Equals("TRUE"))
            {
                string oo = JObject.Parse(tmp2)["data"]["rows"].ToString();
                tmp1.AddRange(JsonConvert.DeserializeObject<List<MatModel>>(oo, jSetting));

                int sum = JObject.Parse(tmp2)["data"]["totalpage"].Value<int>();
                if (sum == i)
                {
                    break;
                }
            }
            i = i + 1;

        }
        return tmp1;
    }

    public string GetMatList(int page)
    {
        string jsonDate = " {" +
                            "	\"pagesize\":100000,  " +
            "        \"page\":" + page + ",  " +
                "\"search\":\"\"," +
                "\"enable\":\"-1\"," +
                "\"parent\":[]," +
                "\"selectfields\":\"refistrationnumber\"," +
                "\"starttime\":-1," +
                "\"endtime\":-1" +
                "} ";



        string url = "http://api.kingdee.com/jdy/basedata/material_list?access_token=" + accessToken;

        string rt = "";
        rt = postCustApiClient(url, jsonDate);
        return rt;

    }

    // 获取销售出库单------------开发蓝信药监做的供参考
    public string GetKdSaleData1()
    {
        var jSetting = new JsonSerializerSettings();
        jSetting.NullValueHandling = NullValueHandling.Ignore;

        string vtoken = token;


        //  一 、获取预查询数据
        string url = "http://api.kingdee.com/jdy/sal/sal_outbound_list?access_token=" + vtoken;
        string jsonprepram = " { " +
            " 	\"deptid\":\"[]\", " +
            " 	\"empid\":[], " +
            " 	\"billstatus\": \"\", " +
            " 	\"settlestatus\":\"\", " +
            " 	\"currencyid\":[], " +
            " 	\"customerid\":[], " +
            // " 	\"startdate\" : \"" + enddate + "\", " +
            // " 	\"enddate\" : \"" + enddate + "\", " +
            "   \"starttime\":-1, " +
            "   \"endtime\":-1, " +
            " 	\"search\":\"\", " +
            " 	\"payment_flag\":-1, " +
            " 	\"iostatus\":\"\", " +
            " 	\"page\":1, " +
            " 	\"pagesize\":1000, " +
            " 	\"selectfields\":\"createtime,customerid.name\", " +
            " 	\"totalfields\":\"totalunsettleamount\", " +
            " 	\"orderby\":\"createtime desc\", " +
            "   \"top\":0 " +
            " } ";

        string rt = "";
        //string rt = HttpPost(url, jsonprepram);

        /*           List<KDPreInstrumentSale> kdpresale = null;
                   if (JObject.Parse(rt)["success"].Value<string>().ToUpper().Equals("TRUE"))
                   {
                       string oo = JObject.Parse(rt)["data"]["rows"].ToString();
                       kdpresale = JsonConvert.DeserializeObject<List<KDPreInstrumentSale>>(oo, jSetting);
                   }*/







        return rt;
    }

    // 保存销售出库单
    public string SaveKdSaleData(string jsonprepram)
    {


        string url = "http://api.kingdee.com/jdy/sal/sal_outbound_save?access_token=" + accessToken;

        string rt = "";
        rt = postCustApiClient(url, jsonprepram);
        return rt;
    }

    #endregion



    public ResponseModel<InstrumentSale> GetKdSaleData(string para, string enddate)
    {
        var jSetting = new JsonSerializerSettings();
        jSetting.NullValueHandling = NullValueHandling.Ignore;

        //  一 、获取预查询数据
        string jsonDate = " { " +
            " 	\"deptid\":\"[]\", " +
            " 	\"empid\":[], " +
            " 	\"billstatus\": \"\", " +
            " 	\"settlestatus\":\"\", " +
            " 	\"currencyid\":[], " +
            " 	\"customerid\":[], " +
            " 	\"startdate\" : \"" + enddate + "\", " +
            " 	\"enddate\" : \"" + enddate + "\", " +
            "   \"starttime\":-1, " +
            "   \"endtime\":-1, " +
            " 	\"search\":\"\", " +
            " 	\"payment_flag\":-1, " +
            " 	\"iostatus\":\"\", " +
            " 	\"page\":1, " +
            " 	\"pagesize\":1000, " +
            " 	\"selectfields\":\"createtime,customerid.name\", " +
            " 	\"totalfields\":\"totalunsettleamount\", " +
            " 	\"orderby\":\"createtime desc\", " +
            "   \"top\":0 " +
            " } ";

        string url = "http://api.kingdee.com/jdy/sal/sal_outbound_list?access_token=" + accessToken;
        List<KDPreInstrumentSale> kdpresale = new List<KDPreInstrumentSale>();
        string rt = postCustApiClient(url, jsonDate);

        if (JObject.Parse(rt)["success"].Value<string>().ToUpper().Equals("TRUE"))
        {
            string oo = JObject.Parse(rt)["data"]["rows"].ToString();
            kdpresale = JsonConvert.DeserializeObject<List<KDPreInstrumentSale>>(oo, jSetting);
        }



        // 二 、 获取单据明细 并组装数据
        List<InstrumentSale> islist = new List<InstrumentSale>();
        foreach (KDPreInstrumentSale kdpis in kdpresale)
        {
            string jsonpram = " {\"number\":\"" + kdpis.billno + "\"}";
            string oom = postCustApiClient("http://api.kingdee.com/jdy/sal/sal_outbound_detail?access_token=" + accessToken, jsonpram);
            string ooma = JObject.Parse(oom)["data"].ToString();
            KDInstrumentSale kdis = JsonConvert.DeserializeObject<KDInstrumentSale>(ooma, jSetting);

            foreach (KDInstrumentSaleEntity kdise in kdis.material_entity)
            {
                islist.Add(new InstrumentSale()
                {
                    SALE_NO = kdis.billno,
                    SALE_DATE = kdis.billdate,
                    INSTRUMENT_CODE = kdise.materialid_number,
                    INSTRUMENT_NAME = kdise.materialid_name,
                    REGIST_NO = kdise.custom_entity_field__6__22guspuvyz94__materialid__refistrationnumber,
                    BATCH_NO = kdise.batchno,
                    VALIDITY = kdise.validdate,
                    PRODUCER = kdise.custom_entity_field__6__22dyhzdxn4aubl__materialid__custom_field__4__22dyhvyxiew4bixieq,
                    SPEC = kdise.materialid_model,
                    UNIT = kdise.unit_name,
                    QTY = kdise.qty,
                    PURCHASER_NAME = kdis.customerid_name,
                    PURCHASER_CODE = kdpis.customerid_number,
                    DESTROY_NO = ""
                });
            }
        }

        ResponseModel<InstrumentSale> tmp3 = new ResponseModel<InstrumentSale>(false, "失败");
        tmp3.data = islist;
        tmp3.success = true;
        tmp3.message = "成功";
        return tmp3;
    }


    public ResponseModel<InstrumentStore> GetKdInvData(string para, string enddate)
    {
        var jSetting = new JsonSerializerSettings();
        jSetting.NullValueHandling = NullValueHandling.Ignore;

        //  一 、获取商品数据
        int curentpage = 1;
        int totalpage = 1;
        List<Material> kdmat = new List<Material>();

        while (curentpage <= totalpage)
        {
            string urlmatrial = "http://api.kingdee.com/jdy/basedata/material_list?access_token=" + accessToken;
            string jsonmat = "{    " +
                "    \"search\":\"\",  " +
                "    \"enable\":\"-1\",  " +
                "    \"parent\":[],  " +
                "    \"selectfields\":\"refistrationnumber\",  " +
                "    \"starttime\":-1,  " +
                "    \"endtime\":-1,  " +
                "    \"page\":" + curentpage + ",  " +
                "    \"pagesize\":1000  " +
                "    }  ";

            string rtmat = postCustApiClient(urlmatrial, jsonmat);
            if (JObject.Parse(rtmat)["success"].Value<string>().ToUpper().Equals("TRUE"))
            {
                curentpage = (int)JObject.Parse(rtmat)["data"]["page"] + 1;
                totalpage = (int)JObject.Parse(rtmat)["data"]["totalpage"];
                string oo = JObject.Parse(rtmat)["data"]["rows"].ToString();
                kdmat.AddRange(JsonConvert.DeserializeObject<List<Material>>(oo, jSetting));
            }

        }



        //  二 、获取即时库存数据
        string url = "http://api.kingdee.com/jdy/inv/inv_list?access_token=" + accessToken;
        string jsonprepram = "{   " +
                        "    \"auxpropids\":[],   " +
                        "    \"spids\":\"\",   " +
                        "    \"stockids\":[],   " +
                        "    \"materialids\":[],   " +
                        "    \"begindate\":\"\",   " +
                        "    \"expiredate\":\"\",   " +
                        "    \"include_batch_kfperiod\":true,   " +
                        "    \"include_package\":false,   " +
                        "    \"totalfields\":[\"stockid,materialid\"]   " +
                        "    }   ";

        string rt = postCustApiClient(url, jsonprepram);
        List<KDInstrumentInv> kdpresale = new List<KDInstrumentInv>();
        if (JObject.Parse(rt)["success"].Value<string>().ToUpper().Equals("TRUE"))
        {
            string oo = JObject.Parse(rt)["data"]["rows"].ToString();
            kdpresale = JsonConvert.DeserializeObject<List<KDInstrumentInv>>(oo, jSetting);
        }






        // 二 、 获取单据明细 并组装数据
        List<InstrumentStore> islist = new List<InstrumentStore>();
        foreach (KDInstrumentInv kdise in kdpresale)
        {
            Material mt = (Material)kdmat.Where(t => t.number.Equals(kdise.materialid_number)).FirstOrDefault();

            islist.Add(new InstrumentStore()
            {
                INSTRUMENT_CODE = kdise.materialid_number,
                INSTRUMENT_NAME = kdise.materialid_name,
                REGIST_NO = mt.refistrationnumber,
                BATCH_NO = kdise.batchno,
                VALIDITY = kdise.validdate,
                PRODUCER = mt.brandid_name,
                SPEC = kdise.materialid_model,
                UNIT = mt.baseunitid_name,
                QTY = kdise.qty,
                DESTROY_NO = ""
            });

        }


        ResponseModel<InstrumentStore> tmp3 = new ResponseModel<InstrumentStore>(false, "失败");
        tmp3.data = islist;
        tmp3.success = true;
        tmp3.message = "成功";
        return tmp3;

    }

    public ResponseModel<InstrumentStock> GetKdPurData(string para, string enddate)
    {
        var jSetting = new JsonSerializerSettings();
        jSetting.NullValueHandling = NullValueHandling.Ignore;


        //  一 、获取预查询数据
        string jsonprepram = " {  " +
        "     \"deptid\":[], " +
        "     \"empid\":[], " +
        "     \"billstatus\":\"\", " +
        "     \"startdate\" : \"" + enddate + "\", " +
        "     \"enddate\" : \"" + enddate + "\", " +
        "     \"starttime\":-1, " +
        "     \"endtime\":-1, " +
        "     \"startbilldate\":\"\", " +
        "     \"endbilldate\":\"\", " +
        "     \"selectfields\":\"\", " +
        "     \"search\":\"\", " +
        "     \"page\":1, " +
        "     \"pagesize\":1000 " +
        " } ";

        string rt = postCustApiClient("http://api.kingdee.com/jdy/pur/pur_inbound_list?access_token=" + accessToken, jsonprepram);
        List<KDPreInstrumentPur> kdpresale = new List<KDPreInstrumentPur>();
        if (JObject.Parse(rt)["success"].Value<string>().ToUpper().Equals("TRUE"))
        {
            string oo = JObject.Parse(rt)["data"]["rows"].ToString();
            kdpresale = JsonConvert.DeserializeObject<List<KDPreInstrumentPur>>(oo, jSetting);
        }






        // 二 、 获取单据明细 并组装数据
        List<InstrumentStock> islist = new List<InstrumentStock>();
        foreach (KDPreInstrumentPur kdpis in kdpresale)
        {
            string jsonpram = " {\"number\":\"" + kdpis.billno + "\"}";
            string oom = postCustApiClient("http://api.kingdee.com/jdy/pur/pur_inbound_detail?access_token=" + accessToken, jsonpram);
            string ooma = JObject.Parse(oom)["data"].ToString();
            KDInstrumentPur kdis = JsonConvert.DeserializeObject<KDInstrumentPur>(ooma, jSetting);

            foreach (KDInstrumentPurEntity kdise in kdis.material_entity)
            {
                islist.Add(new InstrumentStock()
                {
                    BUY_NO = kdis.billno,
                    PURCHASE_DATE = kdis.billdate,
                    INSTRUMENT_CODE = kdise.materialid_number,
                    INSTRUMENT_NAME = kdise.materialid_name,
                    REGIST_NO = kdise.materialid_refistrationnumber,
                    BATCH_NO = kdise.batchno,
                    VALIDITY = kdise.validdate,
                    PRODUCER = kdise.custom_entity_field__6__22ghpxiehohfly__materialid__custom_field__4__22dyhvyxiew4bixieq,
                    SPEC = kdise.materialid_model,
                    UNIT = kdise.unit_name,
                    QTY = kdise.qty,
                    PROVIDER_NAME = kdis.supplierid_name,
                    PROVIDER_CODE = kdpis.supplierid_number,
                    DESTROY_NO = ""
                });
            }
        }

        ResponseModel<InstrumentStock> tmp3 = new ResponseModel<InstrumentStock>(false, "失败");
        tmp3.data = islist;
        tmp3.success = true;
        tmp3.message = "成功";
        return tmp3;
    }



    public bool initToken()
    {
        // 获取授权信息
        if (GetAcctInfo())
        {
            return GetTokenInfo1();
        }

        else { return false; }
    }

    public bool GetAcctInfo()
    {
        bool rtb = false;

        string url = "/jdyconnector/app_management/push_app_authorize";

        int nonce = new Random().Next(100000000, 999999999);
        int timestamp = (int)(DateTime.Now.ToLocalTime() - DateTime.Parse("1970-01-01").ToLocalTime()).TotalSeconds;

        string queryString = "outerInstanceId=" + HttpUtility.UrlEncode(HttpUtility.UrlEncode(outerInstanceId));


        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.Append("POST");
        stringBuilder.Append('\n');
        stringBuilder.Append(CustUrlEncode(url));
        stringBuilder.Append('\n');
        stringBuilder.Append(queryString);
        stringBuilder.Append('\n');
        stringBuilder.Append("x-api-nonce:" + nonce.ToString());
        stringBuilder.Append('\n');
        stringBuilder.Append("x-api-timestamp:" + timestamp.ToString());
        stringBuilder.Append('\n');
        string signature = HmacSHA256(ClientSecret, stringBuilder.ToString());


        HttpClient _client = new HttpClient();
        _client.Timeout = TimeSpan.FromSeconds(10);
        _client.DefaultRequestHeaders.Add("X-Api-Nonce", nonce.ToString());
        _client.DefaultRequestHeaders.Add("X-Api-Auth-Version", "2.0");
        _client.DefaultRequestHeaders.Add("X-Api-TimeStamp", timestamp.ToString());
        _client.DefaultRequestHeaders.Add("X-Api-ClientID", ClientID);
        _client.DefaultRequestHeaders.Add("X-Api-Signature", signature);
        _client.DefaultRequestHeaders.Add("X-Api-SignHeaders", "X-Api-Nonce,X-Api-TimeStamp");

        string requestUri = "http://api.kingdee.com" + url + "?" + queryString;

        string rt = _client.PostAsync(requestUri, new StringContent(string.Empty, Encoding.UTF8, "application/json")).Result.Content.ReadAsStringAsync().Result;

        if (200 == JObject.Parse(rt)["code"].Value<int>())
        {
            var jSetting = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                MissingMemberHandling = MissingMemberHandling.Ignore
            };
            acctInfo = JsonConvert.DeserializeObject<AcctInfo>(JArray.Parse(JObject.Parse(rt)["data"].ToString()).First.ToString(), jSetting);
            rtb = true;
        }
        else
        {
            rtb = false;
        }
        return rtb;
    }

    public bool GetTokenInfo1()
    {
        /*AppId*/
        //string app_key = "caBVCbYq";
        //string app_secret = "fec6ea17b0767dfbab131c24d917e5145ac3ee66";
        string app_key = acctInfo.appKey;
        string app_secret = acctInfo.appSecret;

        //计算APP签名
        //通过appSecret对app_key进行HamcSHA256加密
        //以16进制输出，再进行Base64加密。例：app_key = abc，appSecret = abc123，
        //则app_signature = ZDljMTI3NGIyNTE1MTRkYzlkNjc1MDNhYjUzMzgzNWMyY2M4YTdjMzdmNmM3YTVlNDkxMTkzNjdiOTFjNzUyZQ ==
        //string signRet = HmacSHA2562(app_key, app_secret);
        //string signRet16 = StringToHexString(signRet, Encoding.UTF8);//输出16进制
        //string app_signature = Base64Encrypt(signRet);
        string app_signature = HmacSHA256(app_secret, app_key);


        /*访问地址*/

        string url = "/jdyconnector/app_management/kingdee_auth_token";



        /*随机数*/
        var xapinonce = new Random().Next(100000000, 999999999).ToString();


        /*时间戳*/
        int num2 = (int)(DateTime.Now - TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1))).TotalSeconds;//我的不用了
        //int num2 = (int)(DateTime.Now.ToLocalTime() - DateTime.Parse("1970-01-01").ToLocalTime()).TotalSeconds;
        var xapitimestamp = num2.ToString();



        //  二 、签名处理

        /*
             1、请求方式

         */
        string requestMethod = "GET"; // 请求方式（POST、GET、DELETE等均为大写）



        /*
          2、请求地址的path部分

           取请求地址的path部分 /jdyconnector/app_management/kingdee_auth_token

           对path部分进行url编码得到
           %2Fjdyconnector%2Fapp_management%2Fkingdee_auth_token
        */



        //string urlEn = HttpUtility.UrlEncode(url);//这个是对字符串进行编码
        string urlEn = CustUrlEncode(url);

        /*
        3、params请求参数
 
        app_key=bVZgAZOv1
        app_signature=MzZlYTk0ODk4MWZlNjdiODNmNWU4YzViNzYxNGM5MTFlOGJkN2NjMzk0MTJkZGNhZGM0NzZhN2YxZDJmOTlkZA==

        分别对参数值进行第一次url编码得到

        app_key=bVZgAZOv1
        app_signature=MzZlYTk0ODk4MWZlNjdiODNmNWU4YzViNzYxNGM5MTFlOGJkN2NjMzk0MTJkZGNhZGM0NzZhN2YxZDJmOTlkZA%3D%3D

        分别对参数值进行第二次url编码得到

        app_key=bVZgAZOv1
        app_signature=MzZlYTk0ODk4MWZlNjdiODNmNWU4YzViNzYxNGM5MTFlOGJkN2NjMzk0MTJkZGNhZGM0NzZhN2YxZDJmOTlkZA%253D%253D

        拼接params请求参数部分（按ASCII码升序顺序进行排序）

        app_key=bVZgAZOv1&app_signature=MzZlYTk0ODk4MWZlNjdiODNmNWU4YzViNzYxNGM5MTFlOGJkN2NjMzk0MTJkZGNhZGM0NzZhN2YxZDJmOTlk

         */

        string app_key1 = HttpUtility.UrlEncode(app_key);//这个是对字符串进行编码
        string app_signature1 = HttpUtility.UrlEncode(app_signature);//这个是对字符串进行编码

        string app_key2 = HttpUtility.UrlEncode(app_key1);//这个是对字符串进行编码
        string app_signature2 = HttpUtility.UrlEncode(app_signature1);//这个是对字符串进行编码

        string paramsStr = "app_key=" + app_key2 + "&app_signature=" + app_signature2;


        /*
         5、拼接得到签名字符串
        每段签名字符拼接均需要换行符（x-api-timestamp时间戳后需要换行符）
        GET
        %2Fjdyconnector%2Fapp_management%2Fkingdee_auth_token
        app_key=bVZgAZOv1&app_signature=MzZlYTk0ODk4MWZlNjdiODNmNWU4YzViNzYxNGM5MTFlOGJkN2NjMzk0MTJkZGNhZGM0NzZhN2YxZDJmOTlkZA%253D%253D
        x-api-nonce:4427456950
        x-api-timestamp:1670305063559
         */

        string signStr =
            requestMethod + "\n"
            + urlEn + "\n"
            + paramsStr + "\n"
            + "x-api-nonce:" + xapinonce + "\n"
            + "x-api-timestamp:" + xapitimestamp + "\n";




        /*
        6、签名字符串生成X-Api-Signature
        假设
        clientId: 200421
        clientSecret: f2adcfef73369bfc4e1384677d38a0ff
        以clientSecret作为密钥，使用HMAC-SHA256算法对签名字符串进行加密以16进制格式输出
        示例：
         */

        //string sigstrm = SHAHelper.HmacSHA256 (ClientSecret, signStr);
        //string sigstrm16 = StringToHexString(sigstrm, Encoding.UTF8);//输出16进制
        //string XApiSignature = Base64Encrypt(sigstrm);
        string XApiSignature = HmacSHA256(ClientSecret, signStr);




        //  三 、开始请求数据

        /*

         curl --location --request GET 'https://api.kingdee.com/jdyconnector/app_management/kingdee_auth_token?app_key=bVZgAZOv1&app_signature=MzZlYTk0ODk4MWZlNjdiODNmNWU4YzViNzYxNGM5MTFlOGJkN2NjMzk0MTJkZGNhZGM0NzZhN2YxZDJmOTlkZA%3D%3D' \
        --header 'Content-type: application/json;charset=utf-8' \
        --header 'X-Api-ClientID: 200421' \
        --header 'X-Api-Auth-Version: 2.0' \
        --header 'X-Api-TimeStamp: 1670305063559' \
        --header 'X-Api-Nonce: 4427456950' \
        --header 'X-Api-SignHeaders: X-Api-TimeStamp,X-Api-Nonce' \
        --header 'X-Api-Signature: OTFiZTliNDFiMjNkYTI3YzVhNzg4MDI4ZGU3MWY1ZTA5ZTk1NjVlNGM1YTI1ZjIxY2Y5YTA3ZGY2OGI1MGQ1MQ==' \

         */


        bool rtb = false;
        try
        {
            HttpClient _client = new HttpClient();
            _client.Timeout = TimeSpan.FromSeconds(10);

            HttpRequestHeaders tt = _client.DefaultRequestHeaders;

            tt.Add("X-Api-ClientID", ClientID);
            tt.Add("X-Api-Auth-Version", "2.0");
            tt.Add("X-Api-TimeStamp", xapitimestamp);
            tt.Add("X-Api-Nonce", xapinonce);
            tt.Add("X-Api-SignHeaders", "X-Api-TimeStamp,X-Api-Nonce");
            tt.Add("X-Api-Signature", XApiSignature);

            string requestUri = "http://api.kingdee.com" + url + "?app_key=" + app_key1 + "&app_signature=" + app_signature1;

            var task = _client.GetAsync(requestUri).Result.Content.ReadAsStringAsync().Result;

            if (0 == JObject.Parse(task)["errcode"].Value<int>())
            {
                appToken = JObject.Parse(task)["data"]["app-token"].Value<string>();
                accessToken = JObject.Parse(task)["data"]["access_token"].Value<string>();
                rtb = true;
            }
            else
            {
                rtb = false;
            }

        }
        catch (Exception)
        {
            rtb = false;
        }

        return rtb;
    }

    public string CustUrlEncode(string url)
    {
        return HttpUtility.UrlEncode("/" + url.TrimStart('/'))
            .Replace("%2f", "%2F")
            .Replace("(", "%28")
            .Replace(")", "%29");
    }


    private string postCustApiClient(string url, string jsonDate)
    {
        HttpClient _client = new HttpClient();
        _client.Timeout = TimeSpan.FromSeconds(10);

        //_client.DefaultRequestHeaders.Add("Content-Type","application/json");
        _client.DefaultRequestHeaders.Add("groupName", acctInfo.groupName);
        _client.DefaultRequestHeaders.Add("accountId", acctInfo.accountId);
        _client.DefaultRequestHeaders.Add("X-GW-Router-Addr", acctInfo.domain);


        string rt = "";
        //string content = JsonSerializer.Serialize(jsonDate);
        rt = _client.PostAsync(url, new StringContent(jsonDate, Encoding.UTF8, "application/json")).Result.Content.ReadAsStringAsync().Result;
        return rt;
    }


    private string HmacSHA256(string secret, string signContent)
    {
        string s = string.Empty;
        using (HMACSHA256 hMACSHA = new HMACSHA256(Encoding.UTF8.GetBytes(secret)))
        {
            s = ToHexString(hMACSHA.ComputeHash(Encoding.UTF8.GetBytes(signContent)));
        }

        return Convert.ToBase64String(Encoding.UTF8.GetBytes(s));
    }

    private string ToHexString(byte[] bytes)
    {
        string result = string.Empty;
        if (bytes != null)
        {
            StringBuilder stringBuilder = new StringBuilder();
            foreach (byte b in bytes)
            {
                stringBuilder.AppendFormat("{0:x2}", b);
            }

            result = stringBuilder.ToString();
        }

        return result;
    }

}